/**************************************************************
  > File Name: recvcast.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2022年03月09日 星期三 06时18分22秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

#define BUFFSIZE 1024

int main(int argc, char **argv)
{
    if (argc < 3)
    {
        fprintf(stderr, "Usage:\n");
        exit(1);
    }
    
    int sockfd;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket()");
        exit(1);
    }
    
    int val = 1;
    socklen_t len = sizeof(val);
    if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (void *)&val, len) < 0)
    {
        perror("setsockopt()");
        exit(1);
    }
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    inet_pton(AF_INET, argv[1], &addr.sin_addr);
    
    socklen_t addrlen = sizeof(addr);
   
    char sendbuff[BUFFSIZE] = {0};

    while (1)
    {
        fgets(sendbuff, BUFFSIZE, stdin);
        sendto(sockfd, sendbuff, strlen(sendbuff), 0, (struct sockaddr *)&addr, addrlen);
        memset(sendbuff, 0, BUFFSIZE);
    }
    close(sockfd);
    exit(0);
}
